import { nextTick, onMounted, onUnmounted, ref, unref, watch } from 'vue'

export function getDynamicProps(props) {
  const ret = {}

  Object.keys(props).map(key => {
    ret[key] = unref(props[key])
  })

  return ret
}
export default function useForm(props) {
  const { formData } = props
  // 用于保存动态表单实例的引用
  const formRef = ref(null)
  const fieldsValue = ref({})

  const formValue = ref(formData)
  async function getForm() {
    const form = unref(formRef)

    if (!form) {
      alert('表单没实例化ref')
    }
    await nextTick()
    return form
  }

  function register(instance) {
    console.log(instance, 'instance')

    onUnmounted(() => {
      formRef.value = null
    })

    formRef.value = instance

    fieldsValue.value = instance.formModel
    watch(
      () => props,
      () => props && formRef.value.setProps(props),

      {
        immediate: true,
        deep: true,
      }
    )
  }

  const methods = {
    setProps: async formProps => {
      const form = await getForm()

      form.setProps(formProps)
    },
    getFieldsValue: values => {
      const form = unref(formRef)
      if (!form) return {}
      return form.getFieldsValue(values)
    },
    setFieldsValue: async values => {
      const form = await getForm()
      const res = await form.setFieldsValue(values)
      return res
    },
    // 重置表单字段
    resetFields: async obj => {
      const form = await getForm()
      return await form.resetFields(obj)
    },
    clearValidate: async obj => {
      const form = await getForm()
      return await form.clearValidate(obj)
    },
    // 验证表单字段
    validate: async obj => {
      const form = await getForm()
      return await form.validate(obj)
    },
    // 删除某个表单的配置
    removeSchemaByFiled: async fieldsValue => {
      const form = await getForm()
      form.removeSchemaByFiled(fieldsValue)
    },

    // 添加表单配置
    addSchema: async (fields, first = false) => {
      const form = await getForm()
      form.addSchema(fields, first)
    },

    // 更新表单配置
    updateSchema: async fields => {
      const form = await getForm()
      form.updateSchema(fields)
    },
  }
  const state = {
    fieldsValue, // 表单数据
  }
  return [register, methods, state]
}
